<template>
  <section class="custom-filter">
    <a-row :gutter="[12, 12]" type="flex" key="row1">
      <a-col :flex="$store.getters.isMobile ? '100%' : '360px'">
        <a-input-search
            v-model:value="keywords"
            style="width: 100%"
            placeholder="搜索对方名称、房号、合同编号、账单编号"
            @search="onSearch"
        />
      </a-col>
      <a-col flex="auto">
        <template v-for="(item, index) of fastSortList" :key="item.id">
          <a-checkable-tag
              :checked="item.id == checkedFastSordId"
              @change="handleFastSortChange(index)"
          >
            {{ item.name }}
          </a-checkable-tag>
        </template>
      </a-col>
      <a-col
          :flex="$store.getters.isMobile ? '100%' : '200px'"
          :class="$store.getters.isMobile ? 'text-left' : 'text-right'"
      >
        <a-space>
          <a-dropdown v-if="['billList'].includes(from) ? canAddBill : true">
            <a-button type="primary">
              <template #icon>
                <PlusOutlined/>
              </template>
              账单
            </a-button>
            <template #overlay>
              <a-menu @click="addBill">
                <a-menu-item key="income">
                  <a-button type="text">添加收款账单</a-button>
                </a-menu-item>
                <a-menu-item key="payment">
                  <a-button type="text">添加付款账单</a-button>
                </a-menu-item>
              </a-menu>
            </template>
          </a-dropdown>
          <a-dropdown>
            <template #overlay>
              <a-menu @click="handleMenuMoreClick">
                <a-menu-item
                    v-if="
                    ['billList'].includes(from)
                      ? canAddBill && haveImport
                      : haveImport
                  "
                    key="bill_import"
                >批量导入
                </a-menu-item
                >
                <a-menu-item key="approval" v-if="haveApprovalSetting">审批配置</a-menu-item>
              </a-menu>
            </template>
            <a-button>
              更多
              <DownOutlined/>
            </a-button>
          </a-dropdown>
        </a-space>
      </a-col>
    </a-row>
    <a-row class="search-show" align="middle" key="row2">
      <a-col :sm="12" :xl="14">
        <template v-if="Object.keys(filterTags).length">
          <a-tag
              closable
              v-for="(tag, tagKey) in filterTags"
              :key="tagKey"
              color="blue"
              @close="closeFilterTag(tagKey)"
              class="mt-10"
          >
            {{ tag }}
          </a-tag>
        </template>
        <span v-else>未选择筛选字段</span>
      </a-col>
      <a-col :sm="12" :xl="10" class="text-right">
        <a-button
            type="text"
            :disabled="clearDisabled"
            danger
            @click="resetFilter"
        >
          清除选项
        </a-button>
        <a-divider type="vertical"/>
        <a-button type="text" @click="sortManageVisible = true"
        >快捷筛选管理
        </a-button
        >
        <a-divider type="vertical"/>
        <a-button type="text" @click="searchBoxShow = !searchBoxShow">
          {{ searchBoxShow ? "收起" : "展开" }}
          <template #icon>
            <DownOutlined :rotate="searchBoxShow ? 180 : 0"/>
          </template>
        </a-button>
      </a-col>
    </a-row>
    <transition name="slide-fade">
      <section class="search-box" v-show="searchBoxShow">
        <a-form layout="vertical">
          <a-row :wrap="true" key="row3" :gutter="24">
            <template
                v-for="(formItem, formKey) in formItemList"
                :key="formKey"
            >
              <template v-if="formItem.show">
                <a-col
                    :xs="16"
                    :sm="12"
                    :md="8"
                    :lg="6"
                    :order="formItem.order"
                >
                  <a-form-item :label="formItem.title">
                    <!-- 日期范围选择 -->
                    <template v-if="formItem.type == 'rangePicker'">
                      <a-row>
                        <a-col :span="11">
                          <a-date-picker
                              v-model:value="formState[formMap[formKey].start]"
                              style="width: 100%"
                              valueFormat="YYYY-MM-DD"
                              @change="
                              (date, dateString) =>
                                handleRangePickerChange(
                                  dateString,
                                  formKey,
                                  'start'
                                )
                            "
                          >
                          </a-date-picker>
                        </a-col>
                        <a-col :span="2" class="text-center lh-30">
                          <span>~</span>
                        </a-col>
                        <a-col :span="11">
                          <a-date-picker
                              v-model:value="formState[formMap[formKey].end]"
                              valueFormat="YYYY-MM-DD"
                              style="width: 100%"
                              @change="
                              (date, dateString) =>
                                handleRangePickerChange(
                                  dateString,
                                  formKey,
                                  'end'
                                )
                            "
                          >
                          </a-date-picker>
                        </a-col>
                      </a-row>
                    </template>
                    <!-- 日期选择 -->
                    <a-date-picker
                        v-if="formItem.type == 'datePicker'"
                        v-model:value="formState[formKey]"
                        valueFormat="YYYY-MM-DD"
                        @change="
                        (date, dateString) =>
                          handleDatePickerChange({ date, dateString }, formKey)
                      "
                        style="width: 100%"
                    >
                    </a-date-picker>
                    <!-- 单选 -->
                    <a-select
                        v-if="'singleSelect' == formItem.type"
                        v-model:value="formState[formKey]"
                        :options="formItem.options"
                        placeholder="请选择"
                        :allowClear="true"
                        @change="
                        (value, option) =>
                          handleSelectChange(
                            { value, option },
                            formKey,
                            'single'
                          )
                      "
                    >
                    </a-select>
                    <template v-if="'multiSelect' == formItem.type">
                      <a-select
                          v-model:value="formState[formKey]"
                          :options="villageList"
                          placeholder="请选择"
                          :allowClear="true"
                          mode="multiple"
                          optionFilterProp="label"
                          @change="
                          (value, option) =>
                            onVillageChange({ value, option }, formKey)
                        "
                          v-if="formKey == 'village_ids'"
                      >
                      </a-select>
                      <a-select
                          v-model:value="formState[formKey]"
                          :options="buildList"
                          placeholder="请选择"
                          :allowClear="true"
                          @change="
                          (value, option) =>
                            onBuildChange({ value, option }, formKey)
                        "
                          mode="multiple"
                          optionFilterProp="label"
                          v-else-if="formKey == 'build_ids'"
                      >
                      </a-select>
                      <a-select
                          v-model:value="formState[formKey]"
                          :options="formItem.options"
                          placeholder="请选择"
                          :allowClear="true"
                          mode="multiple"
                          optionFilterProp="label"
                          @change="
                          (value, option) =>
                            handleSelectChange(
                              { value, option },
                              formKey,
                              'multiple'
                            )
                        "
                          v-else
                      >
                      </a-select>
                    </template>
                    <!-- 级联 -->
                    <template v-if="'cascader' == formItem.type">
                      <a-cascader
                          v-if="formKey == 'cost_type'"
                          v-model:value="formState.cost_type"
                          :options="costTypeList"
                          :load-data="getCostTypeSub"
                          placeholder="请选择"
                          dropdownClassName="fee-type-cascader-custom"
                          @change="
                          (value, option) =>
                            handleCascaderChange({ value, option }, formKey)
                        "
                      />
                      <a-cascader
                          v-else
                          v-model:value="formState[formKey]"
                          :options="formItem.options"
                          expand-trigger="hover"
                          placeholder="请选择"
                          @change="
                          (value, option) =>
                            handleCascaderChange({ value, option }, formKey)
                        "
                      />
                    </template>
                  </a-form-item>
                </a-col>
              </template>
            </template>
          </a-row>
          <a-row type="flex" justify="space-between">
            <a-col :span="8">
              <a-space>
                <a-button type="primary" ghost @click="handleSearchSetting">
                  设置
                </a-button>
                <a-popconfirm
                    :visible="sortPopVisible"
                    ok-text="确认"
                    cancel-text="取消"
                    @confirm="onFastSortSettingConfirm"
                    @cancel="sortPopVisible = false"
                >
                  <template #icon>
                    <ToolOutlined/>
                  </template>
                  <template #title>
                    <div>
                      <span>筛选项名称：</span>
                      <a-input
                          placeholder="请输入"
                          v-model:value="fastSortName"
                          class="ml-5"
                      />
                    </div>
                    <div class="mt-10">
                      <a-checkbox v-model:checked="fastSortIsDefault"/>
                      <span class="ml-5">设置为默认筛选</span>
                    </div>
                  </template>
                  <a-button @click="sortPopVisible = true"
                  >设为快捷筛选
                  </a-button
                  >
                </a-popconfirm>
              </a-space>
            </a-col>
            <a-col :span="8" class="text-right">
              <a-space>
                <a-button type="primary" @click="onSearch">
                  <template #icon>
                    <SearchOutlined/>
                  </template>
                  搜索
                </a-button>
              </a-space>
            </a-col>
          </a-row>
        </a-form>
      </section>
    </transition>
    <search-setting
        :visible="searchSettingVisible"
        :source="2"
        @cancel="searchSettingVisible = false"
        @success="handleSearchSuccess"
    />
    <sort-manage
        :visible="sortManageVisible"
        :source="2"
        @cancel="sortManageVisible = false"
        @success="handleSortManageSuccess"
    />
    <!-- 支付配置 -->
    <pay-setting
        :visible="payVisible"
        business="bill"
        title="账单"
        @cancel="payVisible = false"
        @request="$utils.commonRequest"
    />

    <!--  批量导入  -->
    <Import
        :visible="visibleImport"
        title="导入账单"
        from="bill"
        :importUrl="importUrl"
        :downloadTemUrl="downloadTemUrl"
        :showError="true"
        @cancelBtn="visibleImport = false"
        @refresh="importSuccess"
    />

    <!--  审批配置  -->
    <BillApprovalSetting
        :visible="approvalVisible"
        @closeModal="closeApproval"
    />

  </section>
</template>

<script>
import {
  computed,
  defineComponent,
  nextTick,
  onActivated,
  reactive,
  ref,
} from "vue";
import {
  PlusOutlined,
  DownOutlined,
  SearchOutlined,
  ToolOutlined,
} from "@ant-design/icons-vue";
import SearchSetting from "./modules/SearchSetting.vue";
import SortManage from "./modules/SortManage.vue";
import store from "../../../store";
import {message, RangePicker} from "ant-design-vue";
import request from "../../../common/utils/request";
import moment from "moment";
import {useRoute, useRouter} from "vue-router";
import {PaySetting} from "bl-common-vue3";
import Import from "@/views/setting/DepartmentUser/modules/Import.vue";
import BLCOMMON from "bl-common-vue3";
import BillApprovalSetting
  from "@/components/contract/CustomFilter/modules/BillApprovalSetting.vue";

const ranges = {
  今天: [moment(), moment()],
  本周: [moment().startOf("week"), moment().endOf("week")],
  本月: [moment().startOf("month"), moment().endOf("month")],
  本年: [moment().startOf("year"), moment().endOf("year")],
};

export default defineComponent({
  props: {
    // 默认开启的筛选项
    haveDefault: {
      type: Boolean,
      default: false,
    },
    // 批量导入按钮
    haveImport: {
      type: Boolean,
      default: false,
    },
    from: {
      type: String,
      default: "",
    },
    // 审批配置按钮
    haveApprovalSetting: {
      type: Boolean,
      default: false,
    },
  },
  components: {
    PlusOutlined,
    DownOutlined,
    SearchOutlined,
    ToolOutlined,
    SearchSetting,
    SortManage,
    PaySetting,
    Import,
    BillApprovalSetting,
  },
  setup(props, context) {
    const $route = useRoute();
    let routeQuery = {};

    const canAddBill = computed(() => {
      return BLCOMMON.utils.getBtnPermission([props.from, "curd", "add"]);
    });

    // 关键词搜索
    const keywords = ref("");

    // 是否展示搜索框
    const searchBoxShow = ref(false);

    // 搜索表单
    const formItemList = reactive({...formMap});
    const formState = reactive({...defaultFormState});

    // 清除按钮是否可点击
    const clearDisabled = computed(() => {
      for (let key in formState) {
        if (!formItemEmpty(key)) {
          return false;
        }
      }
      return true;
    });

    let changedState = {}; // 日期字符串map
    const filterTags = ref({}); // 筛选内容

    // 导入显隐（定制）
    const visibleImport = ref(false);
    const importUrl = ref({
      server: "/org",
      url: "/bill/import",
    });
    const downloadTemUrl = ref({
      server: "/org",
      url: "/bill/import/demoFile",
    });

    const btnImport = () => {
      visibleImport.value = true;
    };

    const importSuccess = () => {
      visibleImport.value = false;
      context.emit("importSuccess");
    };

    // 监听日期选择
    const handleRangePickerChange = (date, key, type) => {
      const formKey = formMap[key][type];
      const formTitle =
          formMap[key].label + (type == "start" ? "起始时间" : "结束时间");
      if (date) {
        // 选择了的日期
        changedState[formKey] = date;
        filterTags.value[formKey] = `${formTitle}：${date}`;
      } else {
        // 去掉了日期选择
        delete filterTags.value[formKey];
        delete changedState[formKey];
      }
    };
    const handleDatePickerChange = (e, key) => {
      console.log(e, key);
      const {date, dateString} = e;
      if (dateString) {
        changedState[key] = dateString;
        filterTags.value[key] = `${formMap[key].title}：${dateString}`;
      } else {
        delete filterTags.value[key];
        delete changedState[key];
      }
    };
    // 监听下拉选择
    const handleSelectChange = (e, key, type) => {
      const {value, option} = e;
      if (formItemEmpty(key)) {
        delete filterTags.value[key];
        delete changedState[key];
      } else {
        if (type == "single") {
          // 单选
          changedState[key] = value;
          filterTags.value[key] = `${formMap[key].title}：${option.label}`;
        } else {
          // 多选
          changedState[key] = value.join(",");
          let showTitle = option.map((item) => item.label);
          showTitle = showTitle.join("、");
          filterTags.value[key] = `${formMap[key].title}：${showTitle}`;
        }
      }
    };

    const handleCascaderChange = (e, key) => {
      let {value, option} = e;
      if (value?.length) {
        option = option.slice(-1);
        changedState[key] = value;
        filterTags.value[key] = `${formMap[key].title}：${option[0].label}`;
      } else {
        delete filterTags.value[key];
        delete changedState[key];
      }
    };

    const formItemEmpty = (key) => {
      return (
          formState[key] == undefined ||
          (Array.isArray(formState[key]) && formState[key].length == 0)
      );
    };

    // 关闭某项筛选
    const closeFilterTag = (key) => {
      formState[key] = defaultFormState[key];
      delete changedState[key];
      delete filterTags.value[key];
      nextTick(() => {
        onSearch();
      });
    };

    // 清除筛选
    const resetFilter = () => {
      initFormState();
      nextTick(() => {
        onSearch();
      });
    };

    const initFormState = () => {
      for (let key in filterTags.value) {
        formState[key] = defaultFormState[key];
        delete filterTags.value[key];
      }
      changedState = {};
      checkedFastSordId.value = 0;
    };

    // 设置搜索选择项-自定义筛选字段
    const searchSettingVisible = ref(false);
    const settingList = ref([]);
    const handleSearchSetting = () => {
      store
          .dispatch("SetSearchSettingList", {
            type: "map",
            data: formItemList,
            source: "bill",
          })
          .then(() => {
            searchSettingVisible.value = true;
          });
    };
    const handleSearchSuccess = () => {
      store
          .dispatch("GetSearchSettingState", {source: "bill"})
          .then((res) => {
            setFormItemList(res);
            searchSettingVisible.value = false;
          });
    };

    // 快捷筛选
    const sortManageVisible = ref(false);
    const handleSortManageSuccess = () => {
      sortManageVisible.value = false;
      getFastSortList();
    };
    const setFormItemList = (state) => {
      for (let key in state) {
        formItemList[key] = state[key];
      }
    };
    const fastSortName = ref("");
    const fastSortIsDefault = ref(false);
    const sortPopVisible = ref(false);
    const onFastSortSettingConfirm = () => {
      if (!fastSortName.value) {
        message.warning("请填写快捷筛选名称");
        return;
      }
      let params = {
        name: fastSortName.value,
        is_default: fastSortIsDefault.value ? 1 : 0,
        needMsg: true,
        type: 2,
      };
      params.content = JSON.stringify(changedState);
      request.post("/org", "/contract/fastSearchSet", params).then((res) => {
        sortPopVisible.value = false;
        message.success(res.msg || "操作成功");
        getFastSortList();
      });
    };
    // 获取快捷筛选列表
    const fastSortList = ref([]);
    const checkedFastSordId = ref(0);
    const getFastSortList = (init = false) => {
      request
          .get("/org", "/contract/fastSearchList", {limit: 5, type: 2})
          .then((res) => {
            fastSortList.value = res.list || [];
            if (init) {
              if (Object.keys(routeQuery).length) {
                handleRouteQuery();
              } else if (fastSortList.value.length) {
                // 初始选中默认快捷筛选
                handleFastSortChange(0);
              } else {
                handleDefaultQuery();
              }
            }
          });
    };
    const handleRouteQuery = () => {
      changedState = {...routeQuery};
      for (let key in changedState) {
        if (formMap[key] && formMap[key].type == "singleSelect") {
          changedState[key] = Number(changedState[key]);
        }
      }
      console.log("handleRouteQuery changedState", changedState);
      nextTick(() => {
        setDataToForm();
        onSearch();
      });
    };

    const handleDefaultQuery = () => {
      if (!props.haveDefault) {
        return;
      }
      changedState = {
        bill_status: "1",
        receivable_start_date: moment().startOf('month').format('YYYY-MM-DD'),
        receivable_end_date: moment().endOf('month').format('YYYY-MM-DD')
      };
      for (let key in changedState) {
        if (formMap[key] && formMap[key].type == "singleSelect") {
          changedState[key] = Number(changedState[key]);
        }
      }
      console.log("handleRouteQuery changedState", changedState);
      nextTick(() => {
        setDataToForm();
        onSearch();
      });
    };
    const handleFastSortChange = (index) => {
      const item = fastSortList.value[index];
      if (checkedFastSordId.value == item.id) {
        return;
      }
      initFormState();
      nextTick(() => {
        checkedFastSordId.value = item.id;
        changedState = item.content;
        // 如果有项目或者楼宇 改变---
        if (changedState?.village_ids?.length) {
          let _villages = [];
          villageAndBuildList.value.forEach((v) => {
            if (changedState.village_ids.includes(v.id)) {
              _villages.push(v.id);
            }
          })
          changedState.village_ids = _villages;
          if (!_villages.length) {
            delete changedState.village_ids
          }
        }
        if (changedState?.village_ids?.length) {
          let vbList = villageAndBuildList.value.filter((village) =>
              changedState?.village_ids?.includes(village.id)
          );
          let bList = [];
          vbList.forEach((village) => {
            if (village.buildList && village.buildList.length > 0) {
              village.buildList.forEach((build) => {
                bList.push({
                  label: build.build_name,
                  value: build.id,
                });
              });
            }
          });
          buildList.value = bList;
        }
        if (changedState?.build_ids?.length) {
          let _builds = [];
          buildList.value.forEach((v) => {
            if (changedState.build_ids.includes(v.value)) {
              _builds.push(v.value);
            }
          });
          changedState.build_ids = _builds;
          if (!_builds.length) {
            delete changedState.build_ids;
          }
        }
        setDataToForm();
        onSearch();
      });
    };
    const setDataToForm = () => {
      filterTags.value = {};
      console.log("setDataToForm", changedState);
      let title = "";
      for (let key in changedState) {
        let content = "";
        if (formMap[key]) {
          if (formMap[key].type == "cascader") {
            title = formMap[key].title;
            if (key == "cost_type") {
              let costTitle = formMap[key].title;
              formState[key] = changedState[key];
              costTypeList.value.forEach((item) => {
                if (item.value == formState[key][0] && !item.isLeaf) {
                  let category_id = item.value;
                  request
                      .get("/org", "/bill/costList", {
                        page: 1,
                        limit: 9999,
                        category_id: category_id,
                        status: 1,
                      })
                      .then((res) => {
                        if (res.list) {
                          item.children = res.list.map((item2) => ({
                            label: item2.name,
                            value: item2.cost_type,
                            isLeaf: true,
                          }));
                          item.children.forEach((child) => {
                            if (child.value == formState[key][1]) {
                              content = child.label;
                              filterTags.value['cost_type'] = `${costTitle}：${content}`;
                            }
                          });
                        }
                      });
                }
              });
            } else {
              formState[key] = changedState[key];
              formMap[key].options.forEach((item) => {
                if (item.value == formState[key][0]) {
                  if (formState[key].length == 1) {
                    content = item.label;
                  } else {
                    (item?.children || []).forEach((child) => {
                      if (child.value == formState[key][1]) {
                        content = child.label;
                      }
                    });
                  }
                }
              });
            }
          } else if (formMap[key].type == "multiSelect") {
            const data = formMap[key].isSpecial ? changedState[key] : changedState[key].split(",");
            formState[key] = data.map((item) => {
              if (Number(item)) {
                return Number(item);
              } else {
                return item;
              }
            });
            let result = [];
            if (key === 'village_ids') {
              villageList.value.forEach((item) => {
                if (formState[key].includes(item.value)) {
                  result.push(item.label);
                }
              });
            } else if (key === 'build_ids') {
              buildList.value.forEach((item) => {
                if (formState[key].includes(item.value)) {
                  result.push(item.label);
                }
              });
            } else {
              formMap[key].options.forEach((item) => {
                if (formState[key].includes(item.value)) {
                  result.push(item.label);
                }
              });
            }
            title = formMap[key].title;
            content = result.join("、");
          } else {
            formState[key] = changedState[key];
            const result = formMap[key]?.options?.find(
                (item) => item.value == changedState[key]
            );
            title = formMap[key].title;
            content = result?.label || changedState[key];
          }
        } else {
          for (let formKey in formMap) {
            if (formMap[formKey].start == key) {
              title = formMap[formKey].label + "开始时间";
            }
            if (formMap[formKey].end == key) {
              title = formMap[formKey].label + "结束时间";
            }
            formState[key] = changedState[key];
            content = changedState[key];
          }
        }
        filterTags.value[key] = `${title}：${content}`;
      }
    };

    // 搜索
    const onSearch = () => {
      let params = {...changedState};
      if (keywords.value) {
        params.keywords = keywords.value;
      }
      for (let key in params) {
        if (Array.isArray(params[key]) && formItemList[key].type === 'cascader') {
          params[key] = params[key].slice(-1)[0];
        }
      }
      console.log("onSearchonSearch", params);
      context.emit("search", params);
    };

    // 新建账单
    const $router = useRouter();
    const addBill = (e) => {
      const {key} = e;
      let path = '';
      let title = '';
      if (key == "income") {
        path = 'newIncomeBill';
        title = '收款';
      }
      if (key == "payment") {
        path = 'newPaymentBill';
        title = '付款';
      }
      if (!path) return;
      window.microApp.forceDispatch({
        type: "SetMicroPages",
        microInfo: {
          microId: `org_${path}`,
          app: 'org',
          name: `新建${title}账单`,
          url: `/bill/${path}`,
        }
      })
    };

    // 更多操作
    const payVisible = ref(false);

    // 审批配置
    const approvalVisible = ref(false);
    const handleMenuMoreClick = (e) => {
      const {key} = e;
      if (key == "pay") {
        payVisible.value = true;
      }
      if (key == "bill_import") {
        btnImport();
      }
      if (key == "approval") {
        // 审批配置
        approvalVisible.value = true;
      }
    };

    const closeApproval = () => {
      approvalVisible.value = false;
    };

    const costTypeList = ref([]);
    const getCostTypeList = () => {
      request.get("/org", "/bill/cost/categoryList", {}).then((res) => {
        if (res.list) {
          costTypeList.value = res.list.map((item) => ({
            label: item.name,
            value: item.id,
            isLeaf: false,
          }));

          if (formState.cost_type.length == 2) {
            let category_id = formState.cost_type[0];
            request
                .get("/org", "/bill/costList", {
                  page: 1,
                  limit: 9999,
                  category_id: category_id,
                  status: 1,
                })
                .then((result) => {
                  if (result.list) {
                    costTypeList.value.forEach((item1) => {
                      if (item1.value == category_id) {
                        item1.children = result.list.map((item2) => ({
                          label: item2.name,
                          value: item2.cost_type,
                          isLeaf: true,
                        }));
                      }
                    });
                  }
                });
          }
        }
      });
    };

    const getCostTypeSub = (selectedOptions) => {
      const targetOption = selectedOptions[selectedOptions.length - 1];
      targetOption.loading = true;
      request
          .get("/org", "/bill/costList", {
            page: 1,
            limit: 9999,
            category_id: targetOption.value,
            status: 1,
          })
          .then((res) => {
            if (res.list) {
              targetOption.loading = false;
              targetOption.children = res.list.map((item) => ({
                label: item.name,
                value: item.cost_type,
                isLeaf: true,
              }));
              costTypeList.value = [...costTypeList.value];
            }
          });
    };

    const villageList = ref([]);
    const buildList = ref([]);
    const villageAndBuildList = ref([]);

    const getVillageList = () => {
      return new Promise((resolve) => {
        if (villageAndBuildList.value.length) {
          resolve();
        } else {
          request
              .get("/org", "/build/villageAndBuildList/v2", {
                checked: 1,
              })
              .then((res) => {
                villageAndBuildList.value = res.villageList;
                let vList = [];
                let bList = [];
                res.villageList.forEach((item) => {
                  vList.push({
                    label: item.name,
                    value: item.id,
                  });
                  if (item.buildList && item.buildList.length > 0) {
                    item.buildList.forEach((build) => {
                      bList.push({
                        label: build.build_name,
                        value: build.id,
                      });
                    });
                  }
                });
                villageList.value = vList;
                buildList.value = bList;
                resolve();
              });
        }
      });
    };

    // 切换项目时
    const onVillageChange = (e, key) => {
      let {value, option} = e;
      let vbList = JSON.parse(JSON.stringify(villageAndBuildList.value));
      let bList = [];
      if (value.length > 0) {
        vbList = villageAndBuildList.value.filter((village) =>
            value.includes(village.id)
        );
        changedState[key] = value;
        let labelArr = option.map((item) => item.label);
        filterTags.value[key] = `${formMap[key].title}：${labelArr.join('、')}`;

        // 筛选项目时清除楼宇选中项
        formState["build_ids"] = [];
        delete filterTags.value["build_ids"];
        delete changedState["build_ids"];
      } else {
        delete filterTags.value[key];
        delete changedState[key];
      }

      vbList.forEach((village) => {
        if (village.buildList && village.buildList.length > 0) {
          village.buildList.forEach((build) => {
            bList.push({
              label: build.build_name,
              value: build.id,
            });
          });
        }
      });
      buildList.value = bList;
    };

    const onBuildChange = (e, key) => {
      let {value, option} = e;
      if (value.length > 0) {
        changedState[key] = value;
        let labelArr = option.map((item) => item.label);
        filterTags.value[key] = `${formMap[key].title}：${labelArr.join('、')}`;
      } else {
        delete filterTags.value[key];
        delete changedState[key];
      }
    };

    let initFlag = true;
    const init = () => {
      let _obj = {};
      Object.keys($route.query).forEach((keys) => {
        if (Object.hasOwn(defaultFormState, keys)) {
          _obj[keys] = $route.query[keys];
        }
      });
      routeQuery = _obj;
      // 获取筛选项

      getVillageList().then(() => {
        getCostTypeList();
        store.dispatch("BillInit").then((res) => {
          if (res) {
            for (let key in res) {
              if (formItemList[key] && !formItemList[key].isSpecial) {
                formItemList[key].options = res[key];
              }
            }
            getFastSortList(initFlag);
            initFlag = false;
          }
        });
      });
    };
    onActivated(() => {
      init();
    });

    return {
      ranges,
      keywords,
      searchBoxShow,
      formState,
      formItemList,
      clearDisabled,
      filterTags,
      searchSettingVisible,
      settingList,
      sortManageVisible,
      fastSortName,
      fastSortIsDefault,
      sortPopVisible,
      fastSortList,
      checkedFastSordId,
      handleRangePickerChange,
      handleDatePickerChange,
      handleSelectChange,
      closeFilterTag,
      resetFilter,
      handleSearchSetting,
      handleSearchSuccess,
      handleSortManageSuccess,
      onFastSortSettingConfirm,
      handleFastSortChange,
      onSearch,
      addBill,
      handleCascaderChange,
      handleMenuMoreClick,
      formMap,
      payVisible,
      visibleImport,
      importUrl,
      downloadTemUrl,
      canAddBill,
      importSuccess,
      btnImport,
      costTypeList,
      getCostTypeList,
      getCostTypeSub,
      villageList,
      buildList,
      onVillageChange,
      onBuildChange,
      approvalVisible,
      closeApproval,
    };
  },
});
const defaultFormState = {
  bill_status: [],
  receivable_start_date: null,
  receivable_end_date: null,
  settle_status: [],
  contract_status: [],
  bill_source: [],
  // bill_type: undefined,
  cost_type: [],
  timeout_status: [],
  latefee_status: [],
  // range_time: [],
  lock_status: undefined,
  created_start_at: null,
  created_end_at: null,
  entry_start_date: null,
  entry_end_date: null,
  receipt_status: undefined,
  invoice_status: [],
  invoice_record_status: [],
  currency: [],
  is_forfeit: undefined,
  village_ids: [],
  build_ids: [],
  org_branch_id: [],
  approval_status: undefined,
};
const formMap = {
  bill_status: {
    title: "账单状态",
    order: 1,
    type: "multiSelect",
    show: true,
  },
  receivable_date: {
    title: "应收/付时间",
    label: "应收/付",
    start: "receivable_start_date",
    end: "receivable_end_date",
    order: 2,
    type: "rangePicker",
    show: true,
  },
  settle_status: {
    title: "结清状态",
    order: 3,
    type: "multiSelect",
    show: true,
  },
  contract_status: {
    title: "合同状态",
    order: 4,
    type: "multiSelect",
    show: true,
  },
  bill_source: {
    title: "账单来源",
    order: 5,
    type: "cascader",
    show: true,
  },
  // bill_type: {
  //   title: "账单类型",
  //   order: 6,
  //   type: "singleSelect",
  //   show: true,
  // },
  cost_type: {
    title: "费用类型",
    order: 7,
    type: "cascader",
    show: true,
  },
  timeout_status: {
    title: "逾期状态",
    order: 8,
    type: "multiSelect",
    show: true,
  },
  latefee_status: {
    title: "滞纳金状态",
    order: 9,
    type: "multiSelect",
    show: true,
  },
  start_date: {
    title: "起始时间",
    order: 10,
    type: "datePicker",
    show: true,
  },
  end_date: {
    title: "结束时间",
    order: 10,
    type: "datePicker",
    show: true,
  },
  lock_status: {
    title: "锁定状态",
    order: 11,
    type: "singleSelect",
    show: true,
  },
  created_at: {
    title: "创建时间",
    label: "创建",
    start: "created_start_at",
    end: "created_end_at",
    order: 12,
    type: "rangePicker",
    show: true,
  },
  entry_date: {
    title: "最新入账时间",
    label: "最新入账",
    start: "entry_start_at",
    end: "entry_end_at",
    order: 13,
    type: "rangePicker",
    show: true,
  },
  receipt_status: {
    title: "开具收据状态",
    order: 14,
    type: "singleSelect",
    show: true,
  },
  invoice_status: {
    title: "开具状态",
    order: 15,
    type: "multiSelect",
    show: true,
  },
  invoice_record_status: {
    title: "开票记录状态",
    order: 16,
    type: "multiSelect",
    show: true,
  },
  currency: {
    title: "币种",
    order: 17,
    type: "singleSelect",
    show: true,
  },
  is_forfeit: {
    title: "特殊账单类型",
    order: 18,
    type: "singleSelect",
    show: true,
  },
  village_ids: {
    title: "选择项目",
    order: 19,
    type: "multiSelect",
    isSpecial: true,
    options: [],
    show: true,
  },
  build_ids: {
    title: "选择楼宇",
    order: 20,
    type: "multiSelect",
    isSpecial: true,
    options: [],
    show: true,
  },
  org_branch_id: {
    title: "所属公司",
    order: 21,
    type: "multiSelect",
    show: true,
  },
  approval_status: {
    title: "账单审批类型",
    order: 22,
    type: "singleSelect",
    show: true,
  },
};
</script>

<style lang="less" scoped>
.card {
  border: 1px solid #f4f4f4;
  background: #fff;
  padding: 16px;
}

.custom-filter {
  .tip {
    font-size: 14px;
    color: #666;
  }

  .extra {
    margin-right: 10px;
  }

  .search-show {
    &:extend(.card);
    min-height: 54px;
    margin-top: 16px;
  }

  .search-box {
    &:extend(.card);
  }
}

// 动画效果
.slide-fade-enter-from,
.slide-fade-leave-to {
  //进入前，离开后
  height: 0;
  opacity: 0;
}

.slide-fade-enter-to,
.slide-fade-leave {
  //进入后，离开前
  max-height: 1000px;
}

.slide-fade-enter-active,
.slide-fade-leave-active {
  transition: all 0.1s ease;
}
</style>
